package com.elves.auth.config;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Slf4j
@Configuration
@EnableWebSecurity
public class RoleAuthorizationConfig {

    @Resource
    AppConfig appConfig;

    @Bean // <2>
    @Order(2)
//    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    public SecurityFilterChain standardSecurityFilterChain(HttpSecurity http) throws Exception {
        log.info("exclude:{}", appConfig.getSecurity().getExclude());
        http.authorizeHttpRequests((authorize) -> authorize
                        // 放行静态资源和不需要认证的url
                        .requestMatchers(appConfig.getSecurity().getExclude().toArray(new String[0])).permitAll()
                        .requestMatchers(
                                "/admin/*").hasRole("ADMIN")
                        .requestMatchers(
                                "/user/*").hasRole("USER")
                        .requestMatchers(
                                "/vip/*").hasAnyAuthority("vip", "VIP", "ROLE_VIP", "SCOPE_profile")
                        .requestMatchers(
                                "/time").hasRole("VIP")
                        .requestMatchers(
                                "/see").hasAnyRole("ADMIN","USER","VIP")
                        .requestMatchers(
                                "/me").hasAnyRole("ADMIN","USER","VIP")
                        .anyRequest().authenticated()
                )
                // 默认页面
                // .formLogin(Customizer.withDefaults());
                // 指定登录页面
                .formLogin(formLogin -> formLogin.loginPage("/login"))
                //指定登出页面
                .logout(logout -> {
                            logout.logoutUrl("/logout")
                                    .logoutSuccessUrl("/bye");
                        }
                )
        ;
        return http.build();
    }
}
